#!/usr/bin/ruby

require 'open-uri'

$root_uri = "http://localhost/luminous/"

$suppressions_l = {}
# parse arguments, woo.
i=0
while i<$*.length
  arg = $*[i]
  if arg =~ /^--suppress=/
    langs = arg.gsub /^--suppress=/, ''
    langs.split(',').each do |l|    
      $suppressions_l[l] = true 
    end
  else
    $root_uri = arg
  end
  i+=1
end

$uri = $root_uri + "/tests/"


puts "Using URL: #{$uri}"
puts "if this is wrong, set it as the first non-named argument when you call this script"
puts 

puts
puts "Suppressing languages"
puts $suppressions_l.keys.join ', '

files = Dir.glob('*/**/*.php')
errors = {}

files.each do |test|
  
  print  "testing " + test + "..."

  test_uri = $uri + test

  begin  
    response = open(test_uri).read.strip   
  rescue Exception => e
    puts e.to_s
    puts "An error occurred, testing was unsuccessful."
    exit(1)
  end
 

  if response == ''
    puts "ok"
  else
    failures = response.split(/(^===Failed(.*?)===End)/mi)
    errs = 0
    suppressed = 0
    failures.each do|f|
      if f =~ /^===failed for language (.*)/i
        lang = $1

        if $suppressions_l.key? lang 
          suppressed+=1
        else
          errs += 1
        end

      end
    end


    if errs > 0
      puts "failed"
      errors[test] = errs
    else
      puts "ok [#{suppressed} suppressed]"
    end  

  end
end

puts
puts "-------------"
if errors.empty?
  puts "All tests passed"
else
  puts "The following tests reported problems"
  errors.each_pair{|f, n| puts $uri + f + " : #{n} problems"}
end
exit(0)
